/**
 * Created by DWUSER on 2016/4/1.
 */
const express = require('express');
const router = express.Router();
const Student = require("../models/student");

router.get('/',  (req, res) => {
    Student.find()
        .select('name code mobile')
        .exec( (err,docs) => {
        if (err) {
            res.status(500);
            res.json(err);
        } else {
            res.status(200);
            res.json(docs);
        }
    });
});

router.get('/detail/:id',  (req, res) => {
    Student.findOne({_id: req.params.id})
        .exec( (err, doc) => {
        if (err) {
            res.status(500);
            res.json(err);
        } else {
            res.status(200);
            res.json(doc);
        }
    });
});

router.post('/create',  (req, res) => {
    Student.create(req.body.student, (err, doc) => {
        if (err) {
            res.status(500);
            res.json(err);
        }
        else{
            res.status(200);
            res.json({
                result : true,
                doc : doc
            });
        }
    });
});

router.post('/:id/remove',  (req, res) => {
    Student.findOneAndRemove({_id: req.params.id},  (err, result) => {
        if (err) {
            res.status(500);
            res.json({
                result: false
            });
        } else {
            res.status(200);
            res.json({result:true});
        }
    });
});

router.post('/:id/update',  (req, res) => {
    Student.findOneAndUpdate({_id: req.params.id}, req.body.student, {new: true},   (err, doc) => {
        if (err) {
            res.status(500);
            res.json(err);
        } else {
            res.status(200);
            res.json({result:true});
        }
    });
});

module.exports = router;